<template>
	<div class="food-manage">
		<!-- 头部区域 -->
		<div class="header">
			<h1>食品管理</h1>
			<div class="header-actions">
				<button class="add-btn" @click="addNewFood">
					<i class="fa fa-plus"></i> 添加新食品
				</button>
			</div>
		</div>

		<!-- 搜索和过滤区域 -->
		<div class="filters">
			<div class="search-box">
				<i class="fa fa-search"></i>
				<input type="text" v-model="searchKeyword" placeholder="搜索食品名称..." @input="handleSearch">
			</div>

			<div class="sort-filter">
				<label>排序：</label>
				<select v-model="sortField" @change="loadFoods">
					<option value="foodId">默认排序</option>
					<option value="foodPrice">价格从低到高</option>
					<option value="foodPrice DESC">价格从高到低</option>
					<option value="foodName">名称 A-Z</option>
				</select>
			</div>

			<div class="page-size">
				<label>每页显示：</label>
				<select v-model="pageSize" @change="loadFoods">
					<option value="5">5条</option>
					<option value="10">10条</option>
					<option value="20">20条</option>
					<option value="50">50条</option>
				</select>
			</div>
		</div>

		<!-- 食品列表 -->
		<div class="food-list">
			<!-- 加载状态 -->
			<div v-if="loading" class="loading">
				<i class="fa fa-spinner fa-spin"></i> 加载中...
			</div>

			<!-- 空状态 -->
			<div v-else-if="foods.length === 0" class="empty">
				<img src="@/assets/empty-box.png" alt="空状态">
				<p>暂无食品数据</p>
				<button @click="addNewFood">添加第一个食品</button>
			</div>

			<!-- 食品列表 -->
			<div v-else class="food-items">
				<div v-for="food in foods" :key="food.foodId" class="food-card">
					<div class="food-image">
						<img :src="food.foodImg || defaultFoodImage" alt="食品图片">
					</div>

					<div class="food-info">
						<h3>{{ food.foodName }}</h3>
						<p class="food-desc">{{ food.foodExplain || '暂无描述' }}</p>

						<div class="food-meta">
							<span class="price">¥{{ food.foodPrice.toFixed(2) }}</span>
							<span class="id">ID: {{ food.foodId }}</span>
						</div>
					</div>

					<div class="food-actions">
						<button class="edit-btn" @click="editFood(food.foodId)">
							<i class="fa fa-edit"></i> 编辑
						</button>
						<button class="delete-btn" @click="deleteFood(food.foodId)">
							<i class="fa fa-trash"></i> 删除
						</button>
					</div>
				</div>
			</div>

			<!-- 分页控件 -->
			<div v-if="totalPages > 1" class="pagination">
				<button @click="prevPage" :disabled="currentPage === 1">
					<i class="fa fa-chevron-left"></i> 上一页
				</button>

				<div class="page-info">
					第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
				</div>

				<button @click="nextPage" :disabled="currentPage === totalPages">
					下一页 <i class="fa fa-chevron-right"></i>
				</button>
			</div>
		</div>

		<!-- 统计信息 -->
		<div class="stats">
			<div class="stat-card">
				<div class="stat-value">{{ totalItems }}</div>
				<div class="stat-label">总食品数量</div>
			</div>
		</div>
	</div>
</template>

<script>
	import defaultFoodImage from '@/assets/default_food.png';
	import emptyBoxImage from '@/assets/empty-box.png';

	export default {
		name: 'FoodManage',
		data() {
			return {
				foods: [], // 食品列表数据
				loading: true, // 加载状态
				searchKeyword: '', // 搜索关键词
				sortField: 'foodId', // 排序字段
				currentPage: 1, // 当前页码
				pageSize: 10, // 每页显示数量
				totalItems: 0, // 总食品数量
				totalPages: 1, // 总页数
				defaultFoodImage, // 默认食品图片
				emptyBoxImage, // 空状态图片
				searchTimer: null // 搜索防抖计时器
			};
		},
		computed: {
			// 获取当前商家信息
			business() {
				return this.$getSessionStorage('business') || {};
			}
		},
		created() {
			// 检查商家是否登录
			if (!this.business || !this.business.businessId) {
				this.$router.push('/businessLogin');
				return;
			}

			// 加载食品数据
			this.loadFoods();
		},
		methods: {
			// 加载食品数据
			async loadFoods() {
				this.loading = true;

				try {
					const response = await this.$axios.post(
						'FoodController/listFoodForManage',
						this.$qs.stringify({
							businessId: this.business.businessId,
							searchKeyword: this.searchKeyword,
							sortField: this.sortField,
							page: this.currentPage,
							pageSize: this.pageSize
						})
					);

					if (response.data && response.data.code === 200) {
						this.foods = response.data.foods || [];
						this.totalItems = response.data.totalItems || 0;
						this.totalPages = Math.ceil(this.totalItems / this.pageSize);
					} else {
						this.$notify({
							title: '加载失败',
							message: response.data?.message || '无法加载食品数据',
							type: 'error'
						});
					}
				} catch (error) {
					console.error('加载食品列表失败:', error);
					this.$notify({
						title: '网络错误',
						message: '无法连接到服务器',
						type: 'error'
					});
				} finally {
					this.loading = false;
				}
			},

			// 处理搜索输入（防抖）
			handleSearch() {
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					this.currentPage = 1;
					this.loadFoods();
				}, 500);
			},

			// 添加新食品
			addNewFood() {
				this.$router.push('/foodEdit');
			},

			// 编辑食品
			editFood(foodId) {
				this.$router.push({
					path: '/foodEdit',
					query: {
						foodId
					}
				});
			},

			// 删除食品
			async deleteFood(foodId) {
			  if (!confirm('确定要删除这个食品吗？此操作不可恢复！')) {
			    return;
			  }
			
			  try {
			    const response = await this.$axios.post(
			      'FoodController/removeFood',
			      this.$qs.stringify({ foodId })
			    );
			
			    const { code, message } = response.data;
			
			    if (code === 200) {
			      alert(message || '食品删除成功');
			      this.loadFoods();
			    } else {
			      alert(message || '删除失败');
			    }
			  } catch (error) {
			    console.error('删除食品失败:', error);
			    alert('删除食品时出错');
			  }
			},

			// 上一页
			prevPage() {
				if (this.currentPage > 1) {
					this.currentPage--;
					this.loadFoods();
				}
			},

			// 下一页
			nextPage() {
				if (this.currentPage < this.totalPages) {
					this.currentPage++;
					this.loadFoods();
				}
			},

			// 跳转到指定页
			goToPage(page) {
				if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
					this.currentPage = page;
					this.loadFoods();
				}
			}
		}
	};
</script>

<style scoped>
	.food-manage {
		max-width: 1200px;
		margin: 0 auto;
		padding: 20px;
		font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
	}

	/* 头部样式 */
	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30px;
		padding-bottom: 15px;
		border-bottom: 1px solid #eee;
	}

	.header h1 {
		font-size: 24px;
		color: #333;
		margin: 0;
	}

	.add-btn {
		background-color: #27ae60;
		color: white;
		border: none;
		padding: 10px 20px;
		border-radius: 4px;
		cursor: pointer;
		font-size: 16px;
		display: flex;
		align-items: center;
		gap: 8px;
		transition: background-color 0.3s;
	}

	.add-btn:hover {
		background-color: #219653;
	}

	/* 过滤区域样式 */
	.filters {
		display: flex;
		gap: 20px;
		margin-bottom: 25px;
		flex-wrap: wrap;
		background: #f8f9fa;
		padding: 15px;
		border-radius: 8px;
	}

	.search-box {
		flex: 1;
		min-width: 250px;
		position: relative;
		display: flex;
		align-items: center;
	}

	.search-box i {
		position: absolute;
		left: 12px;
		color: #999;
	}

	.search-box input {
		width: 100%;
		padding: 12px 15px 12px 40px;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 16px;
		transition: border-color 0.3s;
	}

	.search-box input:focus {
		border-color: #3498db;
		outline: none;
		box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
	}

	.sort-filter,
	.page-size {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.sort-filter label,
	.page-size label {
		white-space: nowrap;
		color: #555;
	}

	.sort-filter select,
	.page-size select {
		padding: 10px 15px;
		border: 1px solid #ddd;
		border-radius: 4px;
		background: white;
		font-size: 14px;
		min-width: 150px;
	}

	/* 食品列表样式 */
	.food-list {
		background: white;
		border-radius: 8px;
		box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
		padding: 25px;
		margin-bottom: 30px;
	}

	.loading {
		text-align: center;
		padding: 40px;
		color: #3498db;
		font-size: 18px;
	}

	.loading i {
		margin-right: 10px;
	}

	.empty {
		text-align: center;
		padding: 40px;
	}

	.empty img {
		width: 150px;
		opacity: 0.7;
		margin-bottom: 20px;
	}

	.empty p {
		color: #7f8c8d;
		font-size: 18px;
		margin-bottom: 20px;
	}

	.empty button {
		background-color: #3498db;
		color: white;
		border: none;
		padding: 10px 20px;
		border-radius: 4px;
		cursor: pointer;
		font-size: 16px;
	}

	.food-items {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
		gap: 20px;
	}

	.food-card {
		border: 1px solid #eee;
		border-radius: 8px;
		overflow: hidden;
		transition: transform 0.3s, box-shadow 0.3s;
		display: flex;
		flex-direction: column;
	}

	.food-card:hover {
		transform: translateY(-5px);
		box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
	}

	.food-image {
		height: 180px;
		overflow: hidden;
		background: #f8f9fa;
	}

	.food-image img {
		width: 100%;
		height: 100%;
		object-fit: cover;
		transition: transform 0.5s;
	}

	.food-card:hover .food-image img {
		transform: scale(1.05);
	}

	.food-info {
		padding: 15px;
		flex: 1;
	}

	.food-info h3 {
		margin-top: 0;
		margin-bottom: 10px;
		color: #2c3e50;
		font-size: 18px;
	}

	.food-desc {
		color: #7f8c8d;
		font-size: 14px;
		margin-bottom: 15px;
		min-height: 40px;
	}

	.food-meta {
		display: flex;
		justify-content: space-between;
		margin-top: 10px;
		padding-top: 10px;
		border-top: 1px dashed #eee;
		font-size: 14px;
	}

	.price {
		font-weight: bold;
		color: #e74c3c;
	}

	.id {
		color: #95a5a6;
	}

	.food-actions {
		display: flex;
		border-top: 1px solid #eee;
	}

	.food-actions button {
		flex: 1;
		padding: 12px;
		border: none;
		background: white;
		cursor: pointer;
		font-size: 14px;
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 6px;
		transition: background-color 0.3s;
	}

	.edit-btn {
		color: #3498db;
		border-right: 1px solid #eee;
	}

	.edit-btn:hover {
		background-color: #e3f2fd;
	}

	.delete-btn {
		color: #e74c3c;
	}

	.delete-btn:hover {
		background-color: #ffebee;
	}

	/* 分页样式 */
	.pagination {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 15px;
		margin-top: 30px;
		padding-top: 20px;
		border-top: 1px solid #eee;
	}

	.pagination button {
		padding: 10px 20px;
		border: 1px solid #ddd;
		background: white;
		border-radius: 4px;
		cursor: pointer;
		display: flex;
		align-items: center;
		gap: 8px;
		transition: all 0.3s;
	}

	.pagination button:hover:not(:disabled) {
		background-color: #3498db;
		color: white;
		border-color: #3498db;
	}

	.pagination button:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.page-info {
		color: #7f8c8d;
		font-size: 14px;
	}

	/* 统计信息样式 */
	.stats {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
		gap: 20px;
		margin-top: 20px;
	}

	.stat-card {
		background: white;
		border-radius: 8px;
		padding: 20px;
		text-align: center;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
		transition: transform 0.3s;
	}

	.stat-card:hover {
		transform: translateY(-5px);
	}

	.stat-value {
		font-size: 32px;
		font-weight: bold;
		color: #3498db;
		margin-bottom: 10px;
	}

	.stat-label {
		color: #7f8c8d;
		font-size: 16px;
	}

	/* 响应式设计 */
	@media (max-width: 768px) {
		.filters {
			flex-direction: column;
		}

		.food-items {
			grid-template-columns: 1fr;
		}

		.header {
			flex-direction: column;
			align-items: flex-start;
			gap: 15px;
		}

		.header-actions {
			width: 100%;
		}

		.add-btn {
			width: 100%;
			justify-content: center;
		}
	}
</style>